// pages/owner/index.js
const app = getApp()
var sliderWidth = 96;
var downloadUrlList = null;

Page({
  /**
   * 页面的初始数据
   */

  data: {
    reserveList: null,
    unReserveList: null,
    weekList: null,
    teacherList: null,
    teacherId: null,
    tabs: ["门店", "教室", "课程", "教师", "会员"],
    activeIndex: 0,
    sliderOffset: 0,
    house: null,
    user: null,
    classroom: null,
    classroomList: null,
    course: null,
    courseList: null,
    roleList: [{ id: 1, name: '客户' }, { id: 2, name: '私教' }, { id: 3, name: '馆主' }],
    courseTypeList: [{ code: "courseType_1", name: '大课' }, { code: "courseType_2", name: '小团课' }, { code: "courseType_3", name: '私教' }],
    selectRole: null,
    selectCourseType: null,
    userList: null,
    inputShowed: false,
    inputVal: "",
    files: [],
    classroom: null,
    createNewOrUpdate: null,
    parentId: null,

    as4_ClassRoom: true,
    as4_Course: true,
    as4_Teacher: true,
  },

  listenerActionSheet: function (e) {
    console.log(e);

    let who = e.currentTarget.dataset.id;
    if (who == "course") {
      this.setData({
        as4_Course: !this.data.as4_Course
      });
    }

    if (who == "class_room") {
      this.setData({
        as4_ClassRoom: !this.data.as4_ClassRoom
      });
    }

    if (who == "teacher") {
      this.setData({
        as4_Teacher: !this.data.as4_Teacher
      });
    }
  },

  showActionSheet() {
    this.setData({
      as4_ClassRoom: !this.data.as4_ClassRoom,
      classroom: null,
      files: [],
      createNewOrUpdate: "新建"
    });
  },

  createNewCourse() {
    this.setData({
      as4_Course: !this.data.as4_Course,
      course: null,
      files: [],
      createNewOrUpdate: "新建"
    });
  },

  // 新建企业时，将当前用户的openid写入，并且设置成店主角色
  wxLogin(_enterpriseId, _roleId) {
    // wx.login({
    //   success: res => {
    //     // 发送 res.code 到后台换取 openId, sessionKey, unionId

    //     wx.request({
    //       url: app.globalData.serverUrl + '/user/getUserByCode',
    //       method: "post",
    //       data: {
    //         code: res.code,
    //         enterpriseId: _enterpriseId,
    //         roleId: _roleId
    //       },
    //       success: function (resp) {
    //         console.log("wxLogin: " + resp);

    //         if (resp.data.success) {
    //           let user = resp.data.data;
    //           app.globalData.sysUser = user;
    //           app.globalData.token = user.token;

    //         }
    //       },
    //       fail: function (error) {
    //         console.error(error);
    //       }
    //     });
    //   }
    // });
  },

  onShareAppMessage: function (e) {
    console.log(e);

    return {
      title: "我要注册",
      imageUrl: "https://goss2.vcg.com/creative/vcg/800/version23/VCG41163752634.jpg",
      // path: "/pages/owner/index?parentId=" + this.data.house.id,
      path: "/pages/createEnterprise/index",
      success: function (res) {
        var shareTickets = res.shareTickets;
        if (shareTickets.length == 0) {
          return false;
        }
        wx.getShareInfo({
          shareTicket: shareTickets[0],
          success: function (res) {
            var encryptedData = res.encryptedData;
            var iv = res.iv;
          }
        })
      },
      fail: function (res) {
        // 转发失败
        console.log(res);
      }
    }
  },

  getUserList() {
    let that = this;

    wx.request({
      url: app.globalData.serverUrl + "/user/queryUserList",
      header: {
        token: app.globalData.token
      },
      success(resp) {
        console.log(resp);
        if (resp.data.success) {
          that.setData({
            userList: resp.data.data
          });
        }
      },
      fail(resp) {
        console.error(resp);
      }
    });
  },

  formSubmit5(e) {
    console.log(e);
    let that = this;

    let object = e.detail.value;
    if (this.data.user != null)
      object.id = this.data.user.id;

    if (this.data.selectRole != null)
      object.roleId = this.data.selectRole.id;
    else
      object.roleId = 1;

    // 更新
    wx.request({
      url: app.globalData.serverUrl + "/user/editUser",
      header: {
        token: app.globalData.token
      },
      method: "POST",
      data: object,
      success(resp) {
        console.log(resp);

        if (resp.data.success) {
          wx.showToast({
            title: '操作成功',
            icon: 'none',
            duration: 2000
          });

          that.setData({
            course: null,
            createNewOrUpdate: '新建'
          });

          downloadUrlList = [];
          that.setData({
            files: []
          });

          that.getUserList();
        }
      },
      fail(resp) {
        console.error(resp);
      }
    });
  },

  getTeacherList() {
    let that = this;

    wx.request({
      url: app.globalData.serverUrl + "/user/queryTeacherList",
      header: {
        token: app.globalData.token
      },
      success(resp) {
        console.log(resp);
        if (resp.data.success) {
          that.setData({
            teacherList: resp.data.data
          });
        }
      },
      fail(resp) {
        console.error(resp);
      }
    });
  },

  // 教师
  formSubmit4(e) {
    console.log(e);
    let that = this;

    let object = e.detail.value;
    if (this.data.user != null)
      object.id = this.data.user.id;

    object.photographList = downloadUrlList;

    // 更新
    wx.request({
      url: app.globalData.serverUrl + "/user/editUser",
      header: {
        token: app.globalData.token
      },
      method: "POST",
      data: object,
      success(resp) {
        console.log(resp);

        if (resp.data.success) {
          wx.showToast({
            title: '操作成功',
            icon: 'none',
            duration: 2000
          });

          that.getTeacherList();
        }
      },
      fail(resp) {
        console.error(resp);
      }
    });
  },

  editTeacher(e) {
    this.setData({
      user: e.currentTarget.dataset.item,
      createNewOrUpdate: '更新',
      as4_Teacher: !this.data.as4_Teacher,
    });

    this.setData({
      files: e.currentTarget.dataset.item.photographList
    });
    downloadUrlList = e.currentTarget.dataset.item.photographList;
  },

  editCourse(e) {
    let that = this;
    this.data.courseTypeList.forEach(function (obj, idex) {
      if (obj.code == e.currentTarget.dataset.item.type) {
        that.setData({
          selectCourseType: obj
        });
      }
    });

    this.setData({
      course: e.currentTarget.dataset.item,
      createNewOrUpdate: '更新',
      as4_Course: !this.data.as4_Course,
    });

    this.setData({
      files: e.currentTarget.dataset.item.photographList
    });
    downloadUrlList = e.currentTarget.dataset.item.photographList;
  },

  deleteCourse(e) {
    var that = this;
    var item = e.currentTarget.dataset.item; //获取当前长按图片下标

    wx.showModal({
      title: '提示',
      content: '确认删除吗？',
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: app.globalData.serverUrl + "/course/deleteCourse",
            header: {
              token: app.globalData.token
            },
            data: {
              id: item.id
            },
            success(resp) {
              console.log(resp);
              if (resp.data.success) {
                that.getCourseList();
              }
            },
            fail(resp) {
              console.error(resp);
            }
          });

        } else if (res.cancel) {
          console.log('点击取消了');
        }
      }
    });
  },

  getCourseList() {
    let that = this;

    wx.request({
      url: app.globalData.serverUrl + "/course/queryCourseList",
      header: {
        token: app.globalData.token
      },
      success(resp) {
        console.log(resp);
        if (resp.data.success) {
          that.setData({
            courseList: resp.data.data
          });
        }
      },
      fail(resp) {
        console.error(resp);
      }
    });
  },

  // 课程
  formSubmit3(e) {
    console.log(e);
    let that = this;

    let object = e.detail.value;
    if (this.data.course != null)
      object.id = this.data.course.id;

    if (this.data.selectCourseType != null)
      object.type = this.data.selectCourseType.code;

    object.photographList = downloadUrlList;

    // 新建或删除
    wx.request({
      url: app.globalData.serverUrl + "/course/createOrEdit",
      header: {
        token: app.globalData.token
      },
      method: "POST",
      data: object,
      success(resp) {
        console.log(resp);

        if (resp.data.success) {
          wx.showToast({
            title: '操作成功',
            icon: 'none',
            duration: 2000
          });

          that.setData({
            course: null,
            createNewOrUpdate: '新建',
            selectCourseType: null
          });

          downloadUrlList = [];
          that.setData({
            files: []
          });

          that.getCourseList();

        } else {
          wx.showToast({
            title: resp.data.errorMsg,
            icon: 'none',
            duration: 2000
          });
        }
      },
      fail(resp) {
        console.error(resp);
      }
    });
  },

  editClassRoom(e) {
    this.setData({
      classroom: e.currentTarget.dataset.item,
      createNewOrUpdate: '更新',
      as4_ClassRoom: !this.data.as4_ClassRoom,
    });

    this.setData({
      files: e.currentTarget.dataset.item.photographList
    });
    downloadUrlList = e.currentTarget.dataset.item.photographList;
  },

  formSubmit1(e) {
    console.log("瑜伽馆新建或编辑: " + JSON.stringify(e));
    let that = this;

    let object = e.detail.value;
    if (that.data.house != null)
      object.id = that.data.house.id;

    object.photographList = downloadUrlList;
    if (this.data.parentId != null)
      object.parentId = this.data.parentId;

    // 有id更新，没id新建
    wx.request({
      url: app.globalData.serverUrl + "/house/createOrEdit",
      method: "POST",
      header: {
        token: app.globalData.token
      },
      data: object,
      success(resp) {
        console.log("更新, success: ", resp);

        if (resp.data.success) {
          wx.showToast({
            title: '操作成功',
            icon: 'none',
            duration: 5000
          });

          if (that.data.parentId != null)
            that.wxLogin(resp.data.data, 3);

        } else {
          wx.showToast({
            title: '操作失败, ' + resp.data.errorMsg,
            icon: 'none',
            duration: 2000
          });
        }
      },
      fail(resp) {
        console.error(resp);
      }
    });

  },

  getClassRoomList() {
    let that = this;

    wx.request({
      url: app.globalData.serverUrl + "/classroom/queryClassRoomList",
      header: {
        token: app.globalData.token
      },
      success(resp) {
        console.log(resp);
        if (resp.data.success) {
          that.setData({
            classroomList: resp.data.data
          });
        }
      },
      fail(resp) {
        console.error(resp);
      }
    });
  },

  deleteClassRoom(e) {
    var that = this;
    var item = e.currentTarget.dataset.item; //获取当前长按图片下标

    wx.showModal({
      title: '提示',
      content: '确认删除吗？',
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: app.globalData.serverUrl + "/classroom/deleteClassRoom",
            header: {
              token: app.globalData.token
            },
            data: {
              id: item.id
            },
            success(resp) {
              console.log(resp);
              if (resp.data.success) {
                that.getClassRoomList();
              }
            },
            fail(resp) {
              console.error(resp);
            }
          });

        } else if (res.cancel) {
          console.log('点击取消了');
        }
      }
    });
  },

  // 教室
  formSubmit2(e) {
    console.log(e);
    let that = this;

    let object = e.detail.value;
    if (this.data.classroom != null)
      object.id = this.data.classroom.id;

    object.photographList = downloadUrlList;

    // 新建或删除
    wx.request({
      url: app.globalData.serverUrl + "/classroom/createOrEdit",
      header: {
        token: app.globalData.token
      },
      method: "POST",
      data: object,
      success(resp) {
        console.log(resp);

        if (resp.data.success) {
          wx.showToast({
            title: '操作成功',
            icon: 'none',
            duration: 2000
          });

          // that.setData({
          //   classroom: null,
          //   createNewOrUpdate: '新建'
          // });

          // downloadUrlList = [];
          // that.setData({
          //   files: []
          // });

          that.getClassRoomList();

        } else {
          wx.showToast({
            title: '操作失败',
            icon: 'none',
            duration: 2000
          });
        }
      },
      fail(resp) {
        console.error(resp);
      }
    });
  },

  // 长按删除图片
  deleteImg: function (e) {
    var that = this;
    var imgs = that.data.files;
    var index = e.currentTarget.dataset.index; //获取当前长按图片下标

    wx.showModal({
      title: '提示',
      content: '确定删除吗？',
      success: function (res) {
        if (res.confirm) {
          console.log('点击确定了');
          imgs.splice(index, 1);
          downloadUrlList.splice(index, 1)

        } else if (res.cancel) {
          console.log('点击取消了');
          return false;
        }
        that.setData({
          files: imgs
        });
      }
    });
  },

  chooseImage() {
    let that = this;

    wx.chooseImage({
      success: function (res) {
        console.log(res);

        that.setData({
          files: that.data.files.concat(res.tempFilePaths)
        });

        res.tempFilePaths.forEach(function (tempFilePath, index) {
          console.log(tempFilePath);

          wx.uploadFile({
            url: 'https://www.yogapro.cn/xiaocx/qiniu/upload',
            filePath: tempFilePath,
            name: 'file',
            formData: {
              'user': 'test'
            },
            success: function (res) {
              console.log(res);

              let data = JSON.parse(res.data);
              if(data.success)
                downloadUrlList.push(data.downloadPath);
              else
              wx.showToast({
                title: '异常: ' + data.errorMsg,
                icon: 'none'
              });
            }
          });
        });

      }
    })
  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },

  showInput: function () {
    this.setData({
      inputShowed: true
    });
  },
  hideInput: function () {
    this.setData({
      inputVal: "",
      inputShowed: false
    });
  },
  clearInput: function () {
    this.setData({
      inputVal: ""
    });
  },
  inputTyping: function (e) {
    this.setData({
      inputVal: e.detail.value
    });
  },

  go2where(e) {
    console.log(e);

    if (e.currentTarget.dataset.url == "1") {
      wx.switchTab({
        url: '../homePage/index'
      });
    }

    if (e.currentTarget.dataset.url == "2") {
      wx.redirectTo({
        url: '../teacher/index'
      });
    }
  },

  editUser(e) {
    console.log(e);
    let that = this;

    that.data.roleList.forEach(function (obj, idx) {
      if (e.currentTarget.dataset.item.roleId == obj.id) {
        that.setData({
          selectRole: obj,
          user: e.currentTarget.dataset.item
        });
      }
    });

  },

  bindPickerChange: function (e) {
    console.log(e)
    if (e.target.id == "a") {
      this.setData({
        selectRole: this.data.roleList[e.detail.value]
      });
    }

    if (e.target.id == "b") {
      this.setData({
        selectedRoom: this.data.roomList[e.detail.value]
      });
    }

    if (e.target.id == "c") {
      this.setData({
        selectCourseType: this.data.courseTypeList[e.detail.value]
      });
    }
  },

  tabClick: function (e) {
    console.log(e);
    let that = this;

    this.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: e.currentTarget.id
    });

    downloadUrlList = [];
    this.setData({
      files: [],
      createNewOrUpdate: '新建'
    });

    if (e.currentTarget.id == 0) {
      if (this.data.house != null) {
        that.setData({
          files: this.data.house.photographList
        });
        downloadUrlList = this.data.house.photographList;
      }
    }

    if (e.currentTarget.id == 1) {
      that.setData({
        classroom: null
      });

      // 查询教室列表
      that.getClassRoomList();
    }

    if (e.currentTarget.id == 2) {
      that.setData({
        course: null,
        selectCourseType: null
      });

      // 查询课程列表
      wx.request({
        url: app.globalData.serverUrl + "/course/queryCourseList",
        header: {
          token: app.globalData.token
        },
        success(resp) {
          console.log(resp);
          if (resp.data.success) {
            that.setData({
              courseList: resp.data.data
            });
          }
        },
        fail(resp) {
          console.error(resp);
        }
      });      
    }

    if (e.currentTarget.id == 3) {
      // 查询教师列表
      that.getTeacherList();
    }

    if (e.currentTarget.id == 4) {
      // 查询用户列表
      that.getUserList();
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("options: " + JSON.stringify(options));
    let that = this;

    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          sliderLeft: (res.windowWidth / that.data.tabs.length - sliderWidth) / 2,
          sliderOffset: res.windowWidth / that.data.tabs.length * that.data.activeIndex
        });
      }
    });

    downloadUrlList = [];

    this.setData({
      user: app.globalData.sysUser,
      parentId: options.parentId == null ? null : options.parentId
    });

    if(this.data.parentId != null)
      this.setData({createNewOrUpdate: '新建'});
    else
      this.setData({ createNewOrUpdate: '更新'});

    wx.getUserInfo({
      success: res => {
        app.globalData.userInfo = res.userInfo
        this.setData({
          userInfo: res.userInfo,
          hasUserInfo: true
        });

        that.wxLogin(res.userInfo);
      }
    });

    // loginByWxCode
    // 获取用户openid如果存在并且是馆主进入编辑状态
    // app.globalData.token = "eyJhbGciOiJIUzI1NiJ9.eyJzeXNVc2VyIjoie1wiYXZhdGFyVXJsXCI6XCJodHRwczovL3d4LnFsb2dvLmNuL21tb3Blbi92aV8zMi9RMGo0VHdHVGZUS0tNTVZvaWN2VGtId2hjRXkxa0c0TFRLNmtpYzRpY0JOZ2JyTDdHc1RBUnE2N2N4RzUxQVNSN0FjR3BicWgyNUJNcElwQXV6MzBLSENHZy8xMzJcIixcImNpdHlcIjpcIkRheGluZ1wiLFwiY3JlYXRlVGltZVwiOlwiMTU0MzI4NzA5MDAwMFwiLFwiZW50ZXJwcmlzZUlkXCI6MixcImdlbmRlclwiOlwiMVwiLFwiaWRcIjoxMCxcImludHJvXCI6XCJcXG7llpzlpb3vvIzmir3ng5_jgIHllp3phZLjgIHng6vlpLTjgIJcIixcIm1vYmlsZVwiOlwiMTg2MTAzNDgwNzVcIixcIm5pY2tOYW1lXCI6XCLmiJHmmK_ogIHliJhcIixcInByb3ZpbmNlXCI6XCJCZWlqaW5nXCIsXCJyZWFsTmFtZVwiOlwi5ZWK546JXCIsXCJyb2xlSWRcIjozfSJ9.zydQsri2nU8CbPbDP4a6FQUtUkg5YTvqnJtjpN13ElE";

    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        var input = {};
        input.code = res.code;
        // input.roleId = 3;
        input.enterpriseId = this.data.enterpriseId;

        wx.request({
          url: app.globalData.serverUrl + '/user/getUserByCode',
          method: "post",
          data: input,
          success: function (resp) {
            console.log("wxLogin: " + resp);

            if (resp.data.success) {
              let user = resp.data.data;
              app.globalData.sysUser = user;
              app.globalData.token = user.token;

              // 查询场馆信息
              wx.request({
                url: app.globalData.serverUrl + "/house/getById",
                header: {
                  token: app.globalData.token
                },
                success(resp) {
                  console.log(resp);
                  if (resp.data.success) {
                    if (resp.data.data != null) {
                      that.setData({
                        house: resp.data.data
                      });

                      // if (resp.data.data.name != null) {
                      //   wx.setNavigationBarTitle({
                      //     title: resp.data.data.name
                      //   });
                      // }

                      that.setData({
                        files: resp.data.data.photographList
                      });

                      downloadUrlList = resp.data.data.photographList;
                    }
                  }
                },
                fail(resp) {
                  console.error(resp);
                }
              });

            }
          },
          fail: function (error) {
            console.error(error);
          }
        });
      }
    });

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  }
})